package com.yoomiito.app.taobao

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import android.view.ViewGroup
import android.webkit.WebChromeClient
import android.webkit.WebView
import android.webkit.WebViewClient
import android.widget.LinearLayout
import cn.droidlover.xdroidmvp.log.XLog
import cn.droidlover.xdroidmvp.net.ApiException
import cn.droidlover.xdroidmvp.net.ApiSubscriber
import cn.droidlover.xdroidmvp.net.XApi
import com.yoomiito.app.base.App
import com.yoomiito.app.base.BaseActivity
import com.yoomiito.app.model.bean.UserInfo
import com.yoomiito.app.net.YmApi
import com.yoomiito.app.showToast
import com.yoomiito.app.utils.L
import java.io.UnsupportedEncodingException
import java.net.URLDecoder

class WebViewSqActivity : BaseActivity<WebViewSqPresenter?>() {
    private var mWebView: WebView? = null

    companion object {
        fun start(context: Context) {
            val intent = Intent(context, WebViewSqActivity::class.java)
            context.startActivity(intent)
        }
    }

    override fun getLayoutId(): Int {
        return 0
    }

    override fun newP(): WebViewSqPresenter = WebViewSqPresenter(App.mAppConfig)

    override fun initData(savedInstanceState: Bundle?) {
        initView()
        showLoading()
//        BaiChuanManagerModule.getInstance().tbLogin("") {
//            when (it) {
//                "1" -> {
//                    getTaoBaoUrl()
//                }
//                "0" -> {
//                    XLog.d("登陆阿里百川失败")
//                    finish()
//                }
//            }
//        }

    }

    private fun initView() {
        val linearLayout = LinearLayout(this, null)
        mWebView = WebView(this)
        mWebView?.settings?.javaScriptEnabled = true
        mWebView?.webViewClient = mWebViewClient
        //启用支持DOM Storage
        mWebView?.settings?.domStorageEnabled = true
        val params = LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT)
        linearLayout.addView(mWebView, params)
        setContentView(linearLayout)
    }

    //H5网页授权
    private fun h5ShouQuanLogin(url: String) {

        // String str1 = "https://oauth.taobao.com/authorize?response_type=code&client_id=25664429&redirect_uri=https://r-api.yoomiito.com/api/v1/user/channel/auth&view=wap&state=105556300422";
//        val alibcShowParams = AlibcShowParams(OpenType.Auto)
//        alibcShowParams.clientType = "taobao"
//        alibcShowParams.backUrl = "alisdk://"
//        alibcShowParams.nativeOpenFailedMode = AlibcFailModeType.AlibcNativeFailModeJumpH5
//
////        AlibcTaokeParams alibcTaokeParams = new AlibcTaokeParams("","","");
////        Map<String, String> trackParams = new HashMap<>();
//        AlibcTrade.openByUrl(this, "", url, mWebView,
//                mWebViewClient, mWebChromeClient,
//                alibcShowParams, null, null, object : AlibcTradeCallback {
//            override fun onTradeSuccess(tradeResult: AlibcTradeResult) {
//                L.i("淘宝授权：$tradeResult")
//            }
//
//            override fun onFailure(code: Int, msg: String) {
//                L.i("淘宝授权失败00：$code   $msg")
//            }
//        })
    }

    /**
     * 要拦截授权成功或者失败的地址
     * https://h5.yoomiito.com/feedback-auth.html?type=success
     * https://h5.yoomiito.com/feedback-auth.html?type=fail
     * https://h5.yoomiito.com/feedback-auth.html?type=fail&desc=重复绑定
     */
    private var sq_code = "-1"
    private val mWebViewClient: WebViewClient = object : WebViewClient() {
        var urlSuccess = "feedback-auth.html?type=success"
        var urlFail = "feedback-auth.html?type=fail"
        override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean {
            L.i("拦截URL: $url")
            //https://r-api.yoomiito.com/api/v1/user/channel/auth?code=9A0Lf37vHTpj0rEi8hzFnOSa4101410&state=105556300422
            if (url.contains(urlSuccess)) {
                sq_code = "1"
                if (!isFinishing) {
//                    Intent intent = new Intent();
//                    intent.putExtra("sq_code", sq_code);
//                    setResult(AllCode.TaoBaoAuthResultCode, intent);
                    userInfo(true, "")
                    return true
                }
            } else if (url.contains(urlFail)) {
                sq_code = "2"
                if (!isFinishing) {
                    val urls = url.split("&").toTypedArray()
                    var msg = ""
                    if (urls.size > 1) {
                        msg = urls[1].substring(5)
                    }
                    val result: String
                    result = try {
                        URLDecoder.decode(msg, "utf-8")
                    } catch (e: UnsupportedEncodingException) {
                        e.printStackTrace()
                        msg
                    }
                    //                    Intent intent = new Intent();
//                    intent.putExtra("sq_code", sq_code);
//                    intent.putExtra(Constant.MSG,result);
//                    setResult(AllCode.TaoBaoAuthResultCode, intent);
                    userInfo(false, result)
                    return true
                }
            }
            return false
        }


        override fun onPageFinished(view: WebView?, url: String?) {
            super.onPageFinished(view, url)
            L.i("")
            dismissLoading()
        }
    }
    private val mWebChromeClient: WebChromeClient = object : WebChromeClient() {
        override fun onProgressChanged(view: WebView?, newProgress: Int) {
            super.onProgressChanged(view, newProgress)
            if (newProgress==100){
                dismissLoading()
            }
        }
    }


    private fun getTaoBaoUrl() {
        YmApi.getYmService()
                .taoBaoUrl
                .compose(bindToLifecycle())
                .compose(XApi.getApiTransformerData())
                .compose(XApi.getScheduler())
                .subscribe(object : ApiSubscriber<String>() {
                    override fun onSuccess(url: String) {
//                        dismissLoading()
                        h5ShouQuanLogin(url)
                    }

                    override fun onFail(error: ApiException) {
                        dismissLoading()
                        handleError(error)
                        finish()
                    }
                })
    }

    private fun userInfo(result: Boolean, msg: String) {
        showLoading()
        YmApi.getYmService()
                .userInfo
                .compose(bindToLifecycle())
                .compose(XApi.getApiTransformerData())
                .compose(XApi.getScheduler())
                .subscribe(object : ApiSubscriber<UserInfo>() {
                    override fun onSuccess(userInfo: UserInfo) {
                        setUserInfo(userInfo)
                        dismissLoading()
                        when {
                            result -> {
                                "授权成功"
                            }
                            TextUtils.isEmpty(msg) -> {
                                "授权失败"
                            }
                            else -> {
                                msg
                            }
                        }.showToast()
                        finish()
                    }

                    override fun onFail(error: ApiException) {
                        dismissLoading()
                        when {
                            result -> {
                                "授权成功"
                            }
                            TextUtils.isEmpty(msg) -> {
                                "授权失败"
                            }
                            else -> {
                                msg
                            }
                        }.showToast()
                        finish()
                    }
                })
    }

    //登录须重写onActivityResult方法
//    public override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
//        CallbackContext.onActivityResult(requestCode, resultCode, data)
//    }

    override fun onBackPressed() {
        if (mWebView?.canGoBack()!!) {
            mWebView?.goBack()
            finish()
        } else {
            finish()
        }
    }

    override fun onDestroy() {
//        AlibcTradeSDK.destory()
        if (mWebView != null) {
            mWebView?.loadDataWithBaseURL(null, "", "text/html", "utf-8", null)
            mWebView?.clearHistory()
            (mWebView?.parent as ViewGroup).removeView(mWebView)
            mWebView?.destroy()
            mWebView = null
        }
        super.onDestroy()
    }
}